import { request } from "../../request/index.js";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';

// pages/add/index.js
Page({
  data: {
    // 控制窗口是否弹出，
    isPop: false,
    // 是否被收养
    status: 0,
    animalId: 0,
    isShow: true
  },

  onLoad (options) {
    this.setData ({
      animalId: options.animalId - 0,
      status: options.status - 0
    })
    console.log("detail："+options.animalId)
  },

  // 弹出窗口
  showPop () {
    if (!wx.getStorageSync('token')) {
      wx.showModal({
        title: '请先登录',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if(result.confirm){
            wx.navigateTo({
              url: '/pages/login/index',
            })
          } else return
        }
      });
    } else {
      this.setData ({
        isPop: true
      })
    }
  },

  // 关闭窗口
  closePop () {
    this.setData ({
      isPop: false
    })
  },

  // 刷新页面
  refreshPage () {
    this.closePop ()
    this.setData ({
      isShow: false
    })
    this.setData ({
      isShow: true
    })
  },

  // 领养
  hanldeSure () {
    if (!wx.getStorageSync('token')) {
      wx.showModal({
        title: '请先登录',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if(result.confirm){
            wx.navigateTo({
              url: '/pages/login/index',
            })
          } else return
        }
      });
    } else {
      wx.showModal({
        title: '是否要养育该流浪动物？',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: async (result) => {
          if(result.confirm){
            const res = await request({
              url: `/animal/animalAdoption?animalId=${this.data.animalId}`,
              method: 'post'
            })
            if (res.resultTypeCode == 200) {
              wx.showToast({
                title: '领养成功',
                icon: 'success',
                duration: 1500,
                success: ()=>{
                  this.setData ({
                    status: 1
                  })
                }
              })
            } else {
              wx.showToast({
                title: '失败：已被领养',
                icon: 'error',
                duration: 1500,
                success: ()=>{
                  this.setData ({
                    status: 1
                  })
                }
              })
            }
          }
        }
      })
    }
  }

})